import json
import aliyunsdkcdn
from aliyunsdkcore import client
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcdn.request.v20180510 import DescribeUserDomainsRequest
from aliyunsdkcdn.request.v20180510 import PushObjectCacheRequest
from aliyunsdkcdn.request.v20180510 import RefreshObjectCachesRequest
from aliyunsdkcdn.request.v20180510 import DescribeRefreshTasksRequest

class aliyun_cdn(object):
    def __init__(self, AccessKeyId, AccessKeySecret, endpoint):
        self.AccessKeyId = AccessKeyId
        self.AccessKeySecret = AccessKeySecret
        self.endpoint = endpoint

    def domain_list(self):
        """获取cdn域名列表"""
        Client = client.AcsClient(
            self.AccessKeyId, self.AccessKeySecret, self.endpoint)

        Domain_List = []

        request = DescribeUserDomainsRequest.DescribeUserDomainsRequest()

        request.set_accept_format('json')  # 设置返回数据格式为json

        request.set_PageNumber(1)  # 取得第几页 取值范围为：1~100000

        request.set_PageSize(50)   # 分页大小，默认20，最大50 取值：1~50之前的任意整数

        result = json.loads(Client.do_action(
            request)).get("Domains").get("PageData")

        # t=json.dumps(result)
        for domain in range(len(result)-1):
            Domain_List.append(result[domain]["DomainName"])
            print(result[domain]["DomainName"])

    def push_cdn(self, file_url):
        """调用cdn接口预热url"""
        Client = client.AcsClient(
            self.AccessKeyId, self.AccessKeySecret, self.endpoint)
        request = PushObjectCacheRequest.PushObjectCacheRequest()

        request.set_ObjectPath(file_url)

        respose = Client.do_action_with_exception(request)

        print(str(respose, encoding='utf-8'))
        
    def refresh_cdn(self, file_url):
        """调用cdn接口刷新url"""

        Client = client.AcsClient(
            self.AccessKeyId, self.AccessKeySecret, self.endpoint)
        request = RefreshObjectCachesRequest.RefreshObjectCachesRequest()
        request.set_accept_format('json')
        
        request.set_ObjectPath(file_url)
        
        response = Client.do_action_with_exception(request)
        # python2:  print(response) 
        print(str(response, encoding='utf-8'))
    def refresh_push_status(self,file_url):
        """获取url刷新预热是否在全网生效"""
        Client = client.AcsClient(
            self.AccessKeyId, self.AccessKeySecret, self.endpoint)

        request = DescribeRefreshTasksRequest.DescribeRefreshTasksRequest()
        request.set_accept_format('json')

        response = Client.do_action_with_exception(request)
        
        print(str(response, encoding='utf-8'))

# t1 = aliyun_cdn(AccessKeyId='<id>', AccessKeySecret='<key>',
#                 endpoint='cn-hangzhou')
# t1.push_cdn('<file>')
